package com.wx.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wx.common.DateUtil;
import com.wx.common.HttpClientUtil;
import com.wx.common.JsonObjectResult;
import com.wx.common.WechatUtil;
import com.wx.entity.WechatUser;
import com.wx.entity.WechatUserAmount;
import com.wx.entity.WechatUserSession;
import com.wx.service.UserService;

@RestController
@RequestMapping("/api")
public class UserController {

	@Autowired
	private UserService userService;

	/**
	 * 用户注册
	 * @param request
	 * @param code
	 * @param encryptedData
	 * @param iv
	 * @param referrer
	 * @return
	 */
	@PostMapping("/user/register")
	@ResponseBody
	public JsonObjectResult user_register(HttpServletRequest request, @RequestParam(value = "code") String code,
			@RequestParam(value = "encryptedData") String encryptedData, @RequestParam(value = "iv") String iv,
			@RequestParam(value = "referrer", required = false) String referrer) {

		// 1.接收小程序发送的code
		// 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
		JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
		// 3.接收微信接口服务 获取返回的参数
		String openid = SessionKeyOpenId.getString("openid");
		String sessionKey = SessionKeyOpenId.getString("session_key");

		JSONObject userJson = WechatUtil.getUserInfo(encryptedData, sessionKey, iv);

		WechatUser user = new WechatUser();
		user.setAvatarUrl(userJson.getString("avatarUrl"));
		user.setCity(userJson.getString("city"));
		user.setDateAdd(DateUtil.getStringDate());
		user.setIpAdd(HttpClientUtil.getIpAddress(request));
		user.setIsIdcardCheck(false);
		user.setIsSeller(false);
		user.setLevelRenew(false);
		user.setNick(userJson.getString("nickName"));
		user.setProvince(userJson.getString("province"));
		user.setSource(0);
		user.setSourceStr("小程序");
		user.setStatus(0);
		user.setStatusStr("默认");
		
		int uid = userService.insert(user);
		
		WechatUserSession session = new WechatUserSession();
		session.setUid(uid);
		session.setOpenid(openid);
		userService.insertUserSession(session);
		
		WechatUserAmount userAmount = new WechatUserAmount();
		userAmount.setUid(uid);
		userAmount.setBalance(new BigDecimal(0));
		userAmount.setFreeze(0.00);
		userAmount.setScore(0);
		userAmount.setTotleConsumed(0.00);
		userService.insertUserAmount(userAmount);

		return new JsonObjectResult(0, null, "session");
	}

	/**
	 * 微信用户登录
	 * 
	 * @param code
	 * @param type
	 * @return
	 */
	@PostMapping("/user/login")
	@ResponseBody
	public JsonObjectResult user_login(HttpServletRequest request,
			@RequestParam(value = "code", required = false) String code,
			@RequestParam(value = "type", required = false) String type) {
		
		JsonObjectResult result = null;
		
		// 1.接收小程序发送的code
		// 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
		JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
		// 3.接收微信接口服务 获取返回的参数
		String openid = SessionKeyOpenId.getString("openid");
		
		WechatUserSession userSession = new WechatUserSession();
		userSession = userService.findByOpenid(openid);
		
		String token = UUID.randomUUID().toString();
		
		if(userSession != null) {
			userSession.setToken(token);
			result = new JsonObjectResult(JSONObject.parseObject(JSON.toJSONString(userSession)));
			
			userService.updateToken(userSession.getUid(), token);
			userService.updateLogin(userSession.getUid(), DateUtil.getStringDate(), HttpClientUtil.getIpAddress(request));
		} else {
			result = new JsonObjectResult(10000, null, "user has not exists");
		}
		
		return result;
	}
	
	/**
	 * 验证token
	 * @param request
	 * @param code
	 * @param type
	 * @return
	 */
	@GetMapping("/user/check-token")
	@ResponseBody
	public JsonObjectResult check_token(@RequestParam(value = "token") String token) {
		return new JsonObjectResult(0, null, "success") ;
	}
	
	/**
	 * 获取用户信息
	 * @param code
	 * @return
	 */
	@GetMapping("/user/detail")
	@ResponseBody
	public JsonObjectResult user_detail(@RequestParam(value = "token") String token) {
		WechatUser user = null;
		Map<String, Object> map = new HashMap<String, Object>();
		JsonObjectResult result = null;
		
		int id = userService.selectUidByToken(token);
		
		if(id != 0) {
			user = userService.selectById(id);
			if(user != null) {
				map.put("base", user);
				result = new JsonObjectResult(JSONObject.parseObject(JSON.toJSONString(map)));
			} else {
				result = new JsonObjectResult(500, null, "system error, not find userinfo");
			}
		} else {
			result = new JsonObjectResult(500, null, "token is error");
		}
		
		return result;
	}
	
	/**
	 * 获取用户资金账户信息
	 * @param token
	 * @return
	 */
	@GetMapping("/user/amount")
	@ResponseBody
	public JsonObjectResult user_amount(@RequestParam(value = "token") String token) {
		WechatUserAmount userAmount = null;
		JsonObjectResult result = null;
		
		Integer id = userService.selectUidByToken(token);
		
		if(id != 0) {
			userAmount = userService.selectAmountByUid(id);
			if(userAmount != null) {
				result = new JsonObjectResult(JSONObject.parseObject(JSON.toJSONString(userAmount)));
			} else {
				result = new JsonObjectResult(500, null, "system error, not find userinfo");
			}
		} else {
			result = new JsonObjectResult(500, null, "token is error");
		}
		
		return result;
	}
	
}
